package com.sgcc.dlsc.monitorredis.config;

import com.alibaba.fastjson.JSON;
import com.sgcc.dlsc.monitorredis.model.bo.Group;
import com.sgcc.dlsc.monitorredis.model.bo.Monitor;
import com.sgcc.dlsc.monitorredis.model.po.NodeInfo;
import com.sgcc.dlsc.monitorredis.service.impl.GetInfoServiceImpl;
import com.sgcc.dlsc.monitorredis.util.CommandProcess;
import com.sgcc.dlsc.monitorredis.util.InfoToNodeUtil;
import com.sgcc.dlsc.monitorredis.util.WebsocketUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisClusterConnection;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.*;

/**
 * @Author: 李孟帅
 * @CreateTime: 2019-10-10 17:57
 * @Description: ${Description}
 */
@Component
public class TimeTask {
    private ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);

    private static Monitor monitor;
    public static Map<String, BlockingQueue<List<Group>>> queueClusterMap = new HashMap<>();
    public static Map<String, List<Group>> clusterMap = new HashMap<>();

    static {
        monitor = new Monitor();
        List<String> clusterNameList = new ArrayList<>();
        HashMap<String, JedisConnectionFactory> map = new HashMap<>();
        monitor.setClusters(map);
        monitor.setClusterNameList(clusterNameList);
        try {
            String result = CommandProcess.syncExec("cat /etc/ansible/redis/clusterConfig");
            if (result.isEmpty()){
                System.out.println("一个集群都没有");
            }else {
                String[] split = result.split("\n</.*>\n\n");
                for (String ss : split) {
                    String[] split1 = ss.split("\n");
                    String clusterName = split1[0].substring(1, split1[0].length() - 1);
                    List<String> nodes = new ArrayList<>();
                    for (String item:split1) {
                        if (item.startsWith("192")) {
                            nodes.add(item + ":6379");
                        }
                    }
                    clusterNameList.add(clusterName);
                    System.out.println("集群:" + clusterName + ":" + nodes.toString());

                    JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(new RedisClusterConfiguration(nodes));
                    redisConnectionFactory.afterPropertiesSet();
                    monitor.getClusters().put(clusterName, redisConnectionFactory);
                }
            }

        } catch (Exception e) {
            System.out.println("异常");
            e.printStackTrace();
        }
    }


    public TimeTask() {
        for (String clusterName : monitor.getClusterNameList()) {
             startTask(clusterName);
        }
    }

    public void startTask(String clusterName){
        executor.scheduleAtFixedRate(new Runnable() {
            private BlockingQueue<List<Group>> queue = new ArrayBlockingQueue<>(10);
            private List<NodeInfo> nodeList = new ArrayList<>();

            @Override
            public void run() {
                JedisConnectionFactory redisConnectionFactory = monitor.getClusters().get(clusterName);
                if (redisConnectionFactory == null) {
                    System.out.println("为空");
                    return;
                }
                nodeList.clear();
                RedisClusterConnection connection = redisConnectionFactory.getClusterConnection();
                Iterable<RedisClusterNode> redisClusterNodes = connection.clusterGetNodes();
                for (RedisClusterNode clusterNode : redisClusterNodes) {
                    String server = clusterNode.toString();
                    Properties info = connection.info(clusterNode);
                    NodeInfo node = InfoToNodeUtil.toNode(info, server);
                    nodeList.add(node);
                }
                nodeList.sort(new Comparator<NodeInfo>() {
                    @Override
                    public int compare(NodeInfo o1, NodeInfo o2) {

                        if (o1.getIp().compareTo(o2.getIp()) > 0) {
                            return 1;
                        }
                        if (o1.getIp().compareTo(o2.getIp()) == 0) {
                            return 0;
                        }

                        return -1;
                    }

                });
                List<Group> groupList = InfoToNodeUtil.setGroup(nodeList);
                clusterMap.put(clusterName,groupList);
                if (queue.size() < 10) {
                    queue.offer(groupList);
                } else {
                    try {
                        queue.take();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    queue.offer(groupList);
                }
                queueClusterMap.put(clusterName, queue);
            }
        }, 2000, 3000, TimeUnit.MILLISECONDS);
    }
    @Bean
    public Monitor getMonitor(){
        return monitor;
    }
}



